<template>
  <div class="left-chart-1">
    <div class="title cursorPointer">产线状况</div>
    <div class="wrap">
      <div id="wrapInner">
        <template v-if="!noData1">
          <div class="lc1-header">
            <i class="status ON"></i>
            <span>正常运行&nbsp;{{ lineCount.orderProducingHoursStr }}</span>
            <i class="status OFF"></i>
            <span>产线停机&nbsp;{{ lineCount.coreEquipStopHoursStr }}</span>
          </div>
          <div class="time-line">
            <span>{{ parseTime(abnormalStartTime, "{h}:{i}") }}</span>
            <div class="time-line-inner">
              <div
                v-for="(step, stepIndex) in abnormalTimeSteps"
                :key="stepIndex"
                class="stop-step"
                :style="{ left: step.left + '%', right: step.right + '%' }"
              ></div>
            </div>
            <span>{{ parseTime(abnormalEndTime, "{h}:{i}") }}</span>
          </div>
          <CustomChart
            class="lc2-chart"
            ref="Chart1"
            :option="option"
            :enableClickOptions="['series.bar', 'xAxis.category']"
            :xAxisSelectable="false"
            @series-bar-click="handleSeriesClick"
            @xAxis-category-click="handlexAxisCategoryClick"
          />
        </template>
        <div v-else class="no-data">暂无数据</div>
      </div>
    </div>

    <el-dialog
      :title="`产线停机详情（${detailTitle} 导致）`"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="1000px"
      v-dialog-drag
      :close-on-click-modal="false"
      :destroy-on-close="true"
      top="10vh"
    >
      <el-button
        type="default"
        size="small"
        style="margin-bottom: 10px"
        @click="handleAnalysis"
        >报表分析</el-button
      >
      <el-table :data="detailData" style="width: 100%" height="300px">
        <el-table-column
          prop="collectTime"
          label="停机开始时间"
          min-width="100"
        >
        </el-table-column>
        <el-table-column prop="overTime" label="停机结束时间" min-width="100">
        </el-table-column>
        <el-table-column
          prop="durationValue"
          label="停机时长(分钟)"
          min-width="80"
        >
          <template slot-scope="{ row }">
            {{ toFix(row.durationValue, 2) }}
          </template>
        </el-table-column>
        <el-table-column label="停机原因" min-width="180">
          <template slot-scope="{ row }">
            <span>{{ row.causeErrorCodeDescs || "-" }}</span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CustomChart from "../../components/CustomChart";
import { getEquipProducingInfo } from "@/api/dashboard/blowIrriagtionSpinLineDaily";
import { transformEmtyValue } from "@/utils/eam";
const lineLabelColor = "#ffffffeb";

export default {
  name: "LeftChart2",
  components: { CustomChart },
  props: {
    orderItem: {
      type: Object,
      default: null,
    },
    lineItem: {
      type: Object,
      default: null,
    },
    dateItem: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      coreEquip: {
        coreEquipName: "",
        coreEquipCode: "",
        coreEquipId: "",
      },
      lineCount: {
        orderProducingHours: 0,
        orderProducingHoursStr: "",
        coreEquipStopHours: 0,
        coreEquipStopHoursStr: "",
      },
      abnormalStartTime: "",
      abnormalEndTime: "",
      abnormalTimeSteps: [], //时间轴条，时间轴内停机状态
      option: {
        color: ["#ff5050", "#5470c6"],
        grid: {
          top: 46,
          right: 40,
          left: 20,
          bottom: 50,
        },
        tooltip: {
          trigger: "axis",
          padding: [5, 10],
          formatter(params) {
            // 第一组数据为异常停机总时长，没有累计百分比
            if (params[0].dataIndex == 0) {
              return `${params[0].name}<br />
              <i class="tooltip-circle" style="background-color:#ff5050;"></i>${
                params[0].seriesName
              }：${transformEmtyValue(params[0].value, "-")}分钟<br />
              <i class="tooltip-circle" style="background-color:#ff5050;"></i>停机次数：${transformEmtyValue(
                params[0].data.stopTimes,
                "-"
              )}次`;
            }
            // 第二组数据为空数据，用于间隔总时长和设备时长的距离，留出空间放置y坐标
            if (params[0].dataIndex == 1) {
              return "";
            }
            return `${params[0].name}<br />
              <i class="tooltip-circle" style="background-color:#ff5050;"></i>${
                params[0].seriesName
              }：${transformEmtyValue(params[0].value, "-")}分钟<br />
              <i class="tooltip-circle" style="background-color:#ff5050;"></i>停机次数：${transformEmtyValue(
                params[0].data.stopTimes,
                "-"
              )}次<br />
              <i class="tooltip-circle" style="background-color:#5470c6;"></i>${
                params[1].seriesName
              }：${transformEmtyValue(params[1].value, "-")}%`;
          },
        },
        legend: {
          // top: "middle",
          // right: 0,
          // orient: "vertical",
          show: false,
          data: [
            {
              name: "停机时长",
              icon: "path://M10 0 H 90 C 100 10, 100 0, 100 100 V 90 C 90 100, 100 100, 0 100 H 10 C 0 90, 0 100, 0 0 V 10 C 10 0, 0 0, 100 0",
              // icon: "path://M8,4 h24 q4,0 4,4 v24 q0,4 -4,4 h-24 q-4,0 -4,-4 v-24 q0,-4 4,-4",
              textStyle: {
                padding: [0, -6],
              },
            },
            {
              name: "累计百分比",
              icon: "path://M10 0 H 90 C 100 10, 100 0, 100 100 V 90 C 90 100, 100 100, 0 100 H 10 C 0 90, 0 100, 0 0 V 10 C 10 0, 0 0, 100 0",
              // icon: "path://M8,4 h24 q4,0 4,4 v24 q0,4 -4,4 h-24 q-4,0 -4,-4 v-24 q0,-4 4,-4",
              textStyle: {
                padding: [0, -6],
              },
            },
          ],
          itemGap: 16,
          textStyle: {
            color: lineLabelColor,
          },
          // itemWidth: 15,
          itemHeight: 13,
        },
        xAxis: {
          data: [],
          triggerEvent: true,
          axisLine: {
            lineStyle: {
              color: lineLabelColor,
            },
          },
          axisLabel: {
            interval: 0,
            color: lineLabelColor,
            rotate: 20,
            formatter(value) {
              return value.indexOf("总时长") == -1
                ? value
                : value.replace("总时长", "\n总时长");
            },
          },
          axisTick: {
            show: false,
          },
        },
        yAxis: [
          {
            name: "时长(分钟)",
            nameGap: 20,
            nameTextStyle: {
              color: lineLabelColor,
            },
            position: "left",
            offset: 0,
            splitLine: {
              show: false,
            },
            axisLine: {
              lineStyle: {
                color: lineLabelColor,
              },
            },
            axisLabel: {
              color: lineLabelColor,
              hideOverlap: true,
            },
            axisTick: {
              show: false,
            },
          },
          {
            name: "累计百分比",
            nameGap: 20,
            nameTextStyle: {
              color: lineLabelColor,
            },
            position: "right",
            splitLine: {
              show: false,
            },
            axisLine: {
              lineStyle: {
                color: lineLabelColor,
              },
            },
            axisLabel: {
              color: lineLabelColor,
              hideOverlap: true,
              formatter(value) {
                return value + "%";
              },
            },
            axisTick: {
              show: false,
            },
            min: 0,
            max: 100,
          },
        ],
        series: [
          {
            name: "停机时长",
            data: [],
            type: "bar",
            label: {
              show: true,
              fontSize: 10,
              lineHeight: 13,
              position: "top",
              color: lineLabelColor,
              formatter: (param) => {
                return `${this.toFix(param.data?.stopTimes || 0, 2)}次\n${
                  param.value
                }`;
              },
            },
            barGap: 0,
            barWidth: 20,
            yAxisIndex: 0,
          },
          {
            name: "累计百分比",
            data: [],
            type: "line",
            label: {
              show: true,
              fontSize: 10,
              position: "bottom",
              color: lineLabelColor,
              formatter: (param) => {
                return `${this.toFix(param.value || 0, 2)}%`;
              },
            },
            yAxisIndex: 1,
          },
        ],
      },
      dialogVisible: false,
      detailEquipId: "",
      detailTitle: "",
      detailData: [],
    };
  },
  computed: {
    noData1() {
      return !this.orderItem || !this.option.xAxis.data?.length;
    },
  },
  methods: {
    async getData() {
      if (!this.orderItem) {
        return;
      }

      const param = {
        orderId: this.orderItem.id,
      };

      try {
        const res = await getEquipProducingInfo(param);
        const {
          coreEquipName,
          coreEquipCode,
          coreEquipId,
          orderProducingHours,
          coreEquipStopHours,
          orderStartTime,
          orderEndTime,
          coreEquipStopTimes,
          coreEquipStops,
          coreEquipStopReasonDetails,
        } = res.data;

        // 核心设备
        this.coreEquip = {
          coreEquipName,
          coreEquipCode,
          coreEquipId,
        };
        // 正常运行/停机小时数
        this.lineCount.orderProducingHours = orderProducingHours;
        this.lineCount.orderProducingHoursStr =
          this.getTimeString(orderProducingHours);
        this.lineCount.coreEquipStopHours = coreEquipStopHours;
        this.lineCount.coreEquipStopHoursStr =
          this.getTimeString(coreEquipStopHours);
        // 时间轴开始/结束时间
        this.abnormalStartTime = orderStartTime;
        this.abnormalEndTime = orderEndTime;
        // 时间轴的渲染数据
        const orderStartStamp = new Date(orderStartTime).getTime();
        const orderEndStamp = new Date(orderEndTime).getTime();
        const durantionTotalStamp = orderEndStamp - orderStartStamp;
        let _abnormalTimeSteps = [];
        coreEquipStops.forEach((ele) => {
          const startStampTime = new Date(ele.collectTime).getTime();
          const endStampTime = new Date(ele.overTime).getTime();
          const _leftValue =
            (100 * (startStampTime - orderStartStamp)) / durantionTotalStamp;
          const _rightValue =
            (100 * (orderEndStamp - endStampTime)) / durantionTotalStamp;
          _abnormalTimeSteps.push({
            left: _leftValue < 0 ? 0 : _leftValue,
            right: _rightValue < 0 ? 0 : _rightValue,
            ...ele,
          });
        });
        this.abnormalTimeSteps = _abnormalTimeSteps;
        // 柏拉图
        const xAxisData = [];
        const seriesData1 = [];
        const seriesData2 = [];
        const stopHoursTotal = coreEquipStopReasonDetails.reduce(
          (prev, next) => {
            return {
              stopHours: (prev.stopHours || 0) + (next.stopHours || 0),
            };
          },
          { stopHours: 0 }
        );
        let prevTotal = 0;
        coreEquipStopReasonDetails.forEach((ele) => {
          xAxisData.push({
            value: ele.causeEquipName,
            ...ele,
          });
          seriesData1.push({
            value: this.toFix(ele.stopHours * 60, 2), // 转换为分钟
            stopMinutes: this.toFix(ele.stopHours * 60, 2), //记录分钟
            ...ele,
          });
          prevTotal += ele.stopHours;
          seriesData2.push({
            value: this.toFix((100 * prevTotal) / stopHoursTotal.stopHours, 2),
          });
        });
        // 注意：都要添加对应的空值，才能使坐标位于第一个异常停机总时长柱子之后，lineseries需要先忽略前两个点
        this.option.xAxis.data = [
          {
            value: "产线停机总时长",
            textStyle: {
              align: "center",
              verticalAlign: "top",
              padding: [3, 0, 0, 0],
            },
          },
          { value: "" },
          ...xAxisData,
        ];
        this.option.series[0].data = [
          {
            value: this.toFix(coreEquipStopHours * 60, 2),
            stopTimes: coreEquipStopTimes,
          },
          { value: null },
          ...seriesData1,
        ];
        this.option.series[1].data = [
          { value: null },
          { value: null },
          ...seriesData2,
        ];
        // 计算yAxis坐标的偏移量
        const wrap1InnerWidth =
          this.$el.querySelector("#wrapInner").offsetWidth -
          (this.option.grid.left || 0) -
          (this.option.grid.right || 0);

        this.option.yAxis[0].offset =
          (-3 * wrap1InnerWidth) / (2 * this.option.xAxis.data.length) - 12;
      } catch (error) {
        this.lineCount.orderProducingHours = 0;
        this.lineCount.coreEquipStopHours = 0;
        this.abnormalStartTime = "";
        this.abnormalEndTime = "";
        this.abnormalTimeSteps = [];
        this.option.xAxis.data = [];
        this.option.series[0].data = [];
        this.option.series[1].data = [];
        console.error(error);
      }
    },
    handleSeriesClick(e) {
      if (e.dataIndex == 0 || e.dataIndex == 1) {
        // 前两条一条是总数，一条是空数据，不弹窗
        return;
      }
      this.dialogVisible = true;

      this.detailEquipId = e.data?.causeEquipId || "";
      this.detailTitle = e.data?.causeEquipName || "";
      this.detailData = e.data?.stops || [];
    },
    handlexAxisCategoryClick(e) {
      try {
        const index = this.option.xAxis.data.findIndex(
          (ele) => ele.value == e.value
        );

        if (index == 0 || index == 1) {
          // 前两条一条是总数，一条是空数据，不弹窗
          return;
        }
        this.dialogVisible = true;

        this.detailEquipId =
          this.option.series[0].data[index]?.causeEquipId || "";
        this.detailTitle =
          this.option.series[0].data[index]?.causeEquipName || "";
        this.detailData = this.option.series[0].data[index]?.stops || [];
      } catch (error) {
        console.error(error);
      }
    },
    getTimeString(hours) {
      if (!hours) {
        return hours || "0小时";
      }
      const hoursString = hours.toString().split(".");
      let hourStr = "";
      let minStr = "";
      if (hoursString[0]) {
        hourStr = hoursString[0] + "小时";
      }
      if (hoursString[1]) {
        minStr = this.toFix(Number(`0.${hoursString[1]}`) * 60, 0) + "分钟";
      }
      return hourStr + " " + minStr;
    },
    handleAnalysis() {
      if (!this.lineItem || !this.dateItem) {
        return;
      }

      this.dialogVisible = false;

      const { lineName, factoryDeptName } = this.lineItem.properties;
      this.$router.push({
        name: "FailureRateAnalysis",
        params: {
          lineName,
          factoryDeptName,
          produceDate: this.dateItem,
          equipId: this.detailEquipId,
          autoScrollBottom: true, //自动滚动到底部
        },
      });
    },
  },
  watch: {
    orderItem: {
      handler() {
        this.getData();
      },
      immediate: true,
    },
  },
};
</script>

<style lang="less" scoped>
.el-carousel {
  width: 100%;
  height: 100%;
}
.left-chart-1 {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .wrap {
    flex: 1;
    padding: 30px 35px;
  }

  #wrapInner {
    flex: 1;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    align-items: center;
  }

  .lc1-header {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    text-align: center;
    i {
      display: inline-block;
      width: 12px;
      height: 12px;
      border-radius: 50%;
      &.ON {
        background-color: #74d047;
      }
      &.OFF {
        background-color: #ff5050;
      }
      &.UNKNOWN {
        background-color: #909399;
      }
    }
  }
  .lc2-chart {
    height: 100%;
    flex: 1;
  }

  .time-line {
    width: 100%;
    height: 20px;
    line-height: 20px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 6px;
    &-inner {
      flex: 1;
      height: 100%;
      background-color: #74d047;
      position: relative;
      .stop-step {
        position: absolute;
        height: 100%;
        background-color: #ff5050;
      }
    }
  }
}
::v-deep {
  .tooltip-circle {
    display: inline-block;
    vertical-align: middle;
    width: 10px;
    height: 10px;
    margin-right: 5px;
    border-radius: 50%;
  }
  .el-dialog__body {
    padding-top: 16px;
  }
}
</style>
